package cn.cqie.attendance.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtUtil {

    /**
     * 过期时间三十分钟
     */
    private static final long EXPIRE_TIME = 30 * 60 * 1000;

    /**
     * 私钥
     */
    private static final String SECRET = "!9fM6q1XBKs@&Xe8cYJNsYz3^";

    /**
     * 校验token是否正确
     * @param token token
     * @param username 用户名
     * @return 结果
     */
    public static boolean verify(String token, String username) {
        try {
            // 根据密码生成JWT校验器
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            // 校验token
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            System.out.println("令牌校验失败");
            return false;
        }
    }

    /**
     * 获取token中的用户名
     * @param token token
     * @return username
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成token签名, EXPIRE_TIME过期
     * @param username username
     * @return 签名
     */
    public static String sign(String username) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.create()
                .withClaim("username", username)
                .withExpiresAt(date)
                .sign(algorithm);
    }
}
